package com.tencent.wuyanzu.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;

import com.tencent.wuyanzu.dao.FoodDao;
import com.tencent.wuyanzu.dao.UserDao;
import com.tencent.wuyanzu.model.Food;
import com.tencent.wuyanzu.model.User;
import com.tencent.wuyanzu.service.RecommendService;

public class RecommendServiceImpl implements RecommendService{
	private static String PATH;
	private ArrayList<ArrayList<Integer>> candidates = new ArrayList<>();
	private ArrayList<Integer> features = new ArrayList<>();
	
	static{
		try {
			PATH = RecommendServiceImpl.class.getClassLoader().getResource("").toURI().getPath()+"/outMember.model";
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}@Autowired
	private UserDao userDao;
	private FoodDao foodDao;

	
	@Override
	public ArrayList<Food> recommend(int uid) {
		User user = userDao.getUser(uid);
		int prefer = user.getPrefer();
		
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(PATH)) );
			String line = null;
			
			for(int i = 0 ; i < 8 ; i++ ){
				line = br.readLine().trim();
				features.add(Integer.parseInt(line));
				ArrayList<Integer> tmp = new ArrayList<Integer>();
				for(int j = 0 ; j < 20 ; j++){
					line = br.readLine().trim();
					tmp.add(Integer.parseInt(line));
				}
				candidates.add(tmp);
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int minDistance = 9;
		int index = 0;
		for (int i = 0; i < 8; i++) {
			int curDis = getDistance(prefer, features.get(i),9);
			if (curDis < minDistance) {
				minDistance = curDis;
				index = i;
			}
		}
		ArrayList<Integer> ids = candidates.get(index);
	
		ArrayList<Food> allFood = new ArrayList<Food>(foodDao.getAllFood());
		ArrayList<Food> res = new ArrayList<Food>();
		
		for(Integer each: ids){
			for(Food eachFood : allFood){
				if(eachFood.getFid()==each){
					res.add(eachFood);
					break;
				}
			}
		}
		
		return res;
		
	}
	
	int getDistance(int n1, int n2, int nBits) {
		int res = 0;
		for (int i = 0; i < nBits; i++) {
			int b1 = n1 % 10;
			int b2 = n2 % 10;
			n1 /= 10;
			n2 /= 10;
			if (b1 != b2)
				res++;
		}
		return res;
	}



}
